package net.weitalk.socket.blocked;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class HelloServer extends Thread {
    private ServerSocket serverSocket;
    
    public int getPort() {
        return serverSocket.getLocalPort();
    }
    
    public void run() {
        try {
            serverSocket = new ServerSocket(0);
            while (true) {
                Socket socket = serverSocket.accept();
                RequestHandler requestHandler = new RequestHandler(socket);
                requestHandler.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        HelloServer server = new HelloServer();
        server.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try (Socket client = new Socket(InetAddress.getLocalHost(), server.getPort())) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(client.getInputStream())
            );
            reader.lines().forEach(System.out::println);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
